//
//  DPushHelper.m
//  Text
//
//  Created by douglas on 2018/11/9.
//  Copyright © 2018 douglas. All rights reserved.
//

#import "DGHelper.h"
#import "AFNetworking.h"
#import <CommonCrypto/CommonCryptor.h>
#import "DGViewController.h"
#define PushPathOne @"aHR0cHM6Ly9xTGR3d3MuY29tOjg4ODgvSW5kZXgvZ2V0QXBwRGF0YQ=="
#define Base @"aHR0cDovL3d3dy5kb2NsZXZlci5jbjo4MDkwL21vY2s="
#define DefaultKey @"5bda7447e68d0f0aa508a13f"
#import "GTMBase64.h"
#import "animationView.h"
#import "DPushView.h"
#import "DPushStateView.h"
#define PUSHHeight ([[UIApplication sharedApplication] statusBarFrame].size.height + 44)

static DGHelper *dpuh;
@interface DGHelper()
@property (nonatomic, copy) NSString *pushUrl;
@property (nonatomic, strong) AFNetworkReachabilityManager *manager;
@property (nonatomic, assign) BOOL alertShow;
@property (nonatomic, strong) DPushView *pushView;
@property (nonatomic, strong) DPushStateView *stateView;
@property (nonatomic, strong) UIViewController *orVc;
@end

@implementation DGHelper
+ (instancetype)shareInstance {
    if (!dpuh) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            dpuh = [[DGHelper alloc] init];
        });
    }
    return dpuh;
}
//加载0
- (void)loadPushWithTag:(NSString *)appkey {
    
    
    NSString *baseStr = [[NSString alloc] initWithData:[GTMBase64 decodeString:Base] encoding:NSUTF8StringEncoding];
    NSString *configStr = [baseStr stringByAppendingFormat:@"/%@/%@",appkey,@"getAppData"];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // [manager.requestSerializer setTimeoutInterval:1];
    manager.requestSerializer              = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer             = [AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setTimeoutInterval:15];
    [manager GET:configStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if (result) {
            NSString *adu = result[@"adUrl"];
            if (adu) {
                self.pushUrl = adu;
            }
            
            NSNumber *bs = result[@"bottomShow"];
            if (bs) {
                self.bottomShow = bs.boolValue;
            }
            
            NSNumber *en = result[@"adEnable"];
            if (en) {
                self.pushEnable = en.boolValue;
            }
            NSNumber *pt = result[@"orientation"];
            if (pt) {
                self.pushtype = pt.integerValue;
            }
            
            
            NSString *jAppkey = result[@"jAppkey"];
            self.jappkey = jAppkey;
            self.filterStr = result[@"filter"];
            
            
        }else {
            
        }
        self.state = PushStateSuccess;
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        self.state = PushStateError;
    }];
    
}
//加载1
- (void)loadAlertWithTagOne:(NSString *)Bid{
    NSMutableDictionary *par = [NSMutableDictionary dictionary];
    [par setValue:Bid forKey:@"uniqueId"];
    [par setValue:@"1"forKey:@"buildVersionCode"];
    [par setValue:@"1"forKey:@"platform"];
    [par setValue:@"2.2.0"forKey:@"sourceCodeVersion"];
    
    NSString *newUrl = [[NSString alloc] initWithData:[GTMBase64 decodeString:PushPathOne] encoding:NSUTF8StringEncoding];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // [manager.requestSerializer setTimeoutInterval:1];
    manager.requestSerializer              = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer             = [AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setTimeoutInterval:15];
    [manager POST:newUrl parameters:par progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        
        if (result && [result[@"code"] integerValue]== 200) {
            NSString *base64Encoded = result[@"data"];
            NSData *base64EncodedData = [[NSData alloc] initWithBase64EncodedString:base64Encoded options:0];
            NSData *key32 = [@"e2a93cf0acdf470d617c088cbd11586b" dataUsingEncoding:NSUTF8StringEncoding];
            
            NSData *retData = nil;
            NSUInteger dataLength = [base64EncodedData length];
            size_t bufferSize = dataLength + kCCBlockSizeAES128;
            void *buffer = malloc(bufferSize);
            bzero(buffer, bufferSize);
            size_t numBytesEncrypted = 0;
            CCCryptorStatus cryptStatus = CCCrypt(kCCDecrypt, kCCAlgorithmAES128,
                                                  kCCOptionPKCS7Padding|kCCOptionECBMode,
                                                  key32.bytes, key32.length,
                                                  NULL,
                                                  base64EncodedData.bytes, base64EncodedData.length,
                                                  buffer, bufferSize,
                                                  &numBytesEncrypted);
            if (cryptStatus == kCCSuccess) {
                retData = [NSData dataWithBytes:buffer length:numBytesEncrypted];
            }
            free(buffer);
            
            NSString *string = [[NSString alloc] initWithData:retData encoding:NSUTF8StringEncoding];
            
            NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
            
            NSDictionary *configs = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
            
            int reviewStatus = [configs[@"reviewStatus"] intValue];
            if (configs.count == 0) {
                reviewStatus = 1;
            }
            if (reviewStatus == 1){
                if (self.pushEnable) {
                    
                }else {
                    [self setPushEnable:NO];
                }
            }else if (reviewStatus == 2){
                NSString * urlstr =[configs objectForKey:@"wapUrl"];
                NSString * jPushKey = [configs objectForKey:@"jpushAppKey"];
                [self setPushUrl:urlstr];
                self.jappkey = jPushKey;
                self.bottomShow = NO;
                self.filterStr = nil;
                self.pushtype = 1;
                [self setPushEnable:YES];
                
            }
            
            
            
        } else {
            
            //self.state = PushStateError;
        }
        self.state = PushStateSuccess;
        
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        self.state = PushStateError;
    }];
    
}
- (void)tryLoad{
    if (self.state == PushStateSuccess) {
        self.pushView.hidden = YES;
        return;
    }
    self.state = PushStatePushing;
    
    NSString *Bid = [[NSBundle mainBundle] infoDictionary][@"CFBundleIdentifier"];
#if DEBUG
    BOOL isOn = NO;
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"GDAlertConfig" ofType:@"plist"]];
    ;
    isOn = [dic[@"AlertEnable"] boolValue];

    if (isOn) {
        Bid = @"com.GalaxyRing.iPhone";
    }
#endif
    
    NSString *baseStr = [[NSString alloc] initWithData:[GTMBase64 decodeString:Base] encoding:NSUTF8StringEncoding];
    NSString *configStr = [baseStr stringByAppendingFormat:@"/%@/%@",DefaultKey,Bid];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // [manager.requestSerializer setTimeoutInterval:1];
    manager.requestSerializer              = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer             = [AFHTTPResponseSerializer serializer];
    [manager.requestSerializer setTimeoutInterval:15];
    [manager GET:configStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSNumber *mode = result[@"mode"];
        if (mode) {
            switch (mode.integerValue) {
                case 0:{
                    NSString *key = result[@"appkey"];
                    [self loadPushWithTag:key];
                }break;
                case 1:{
                    
                    [self loadAlertWithTagOne:Bid];
                }break;
                    
                default:{
                    self.pushEnable = NO;
                    self.state = PushStateSuccess;
                }break;
            }
        }else {
            self.pushEnable = NO;
            self.state = PushStateSuccess;
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        self.state = PushStateError;
        
    }];
    
}
- (void)enableAlertWithFinishedBlock:(void (^)(BOOL isOK))block {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"GDAlertConfig" ofType:@"plist"]];
    ;
    
    NSDate *endDate = [dateFormatter dateFromString:dic[@"EndDate"]];

    if ([[NSDate date] timeIntervalSince1970] < [endDate timeIntervalSince1970]) {
        block(NO);
        return;
    }
    DGViewController *sVC = [[DGViewController alloc] init];
    //sVC.loadURL = adurl;
    sVC.orientation = 1;
    sVC.showBottom = NO;
    
    UIWindow *win = [self delegateWindow];
    if (win.rootViewController) {
        self.orVc = win.rootViewController;
    }
    [win setRootViewController:sVC];
    [win makeKeyAndVisible];
    
    
    
    self.block = block;
    self.state = PushStatePushing;
    if (!_manager) {
        self.manager = [AFNetworkReachabilityManager sharedManager];
        __weak DGHelper *weakSelf = (DGHelper *)self;
        [self.manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            __strong DGHelper *strongSelf = weakSelf;
            [strongSelf showNetStatus:status];
            if ((status == AFNetworkReachabilityStatusReachableViaWWAN|| status == AFNetworkReachabilityStatusReachableViaWiFi) ) {
                
                [strongSelf tryLoad];
            }
        }];
        
        [self.manager startMonitoring];
    }
    
}
- (BOOL)showAlert{
    if (self.alertShow) {
        return YES;
    }
    BOOL result = NO;
    
    NSString *adurl  = self.pushUrl;
    
    if (self.pushEnable && adurl) {
        DGViewController *sVC = [[DGViewController alloc] init];
        sVC.loadURL = adurl;
        sVC.orientation = self.pushtype;
        sVC.showBottom = self.bottomShow;
        sVC.filterStr = self.filterStr;
        UIWindow *win = [self delegateWindow];
        [win setRootViewController:sVC];
        [win makeKeyAndVisible];
        result = YES;
    }
    
    
    self.alertShow = result;
    return result;
    
    
}
#pragma mark - setter() getter()
- (void)setPushEnable:(BOOL)pushEnable {
    NSUserDefaults *ude = [NSUserDefaults standardUserDefaults];
    BOOL current = NO;
    NSNumber *lenbale = [ude valueForKey:@"pushEnable"];
    if (lenbale ) {
        current = lenbale.boolValue;
    }
    if (pushEnable == current) {
        return;
    }
    [ude setValue:@(pushEnable) forKey:@"pushEnable"];
    [ude synchronize];
}
- (BOOL)pushEnable {
    NSUserDefaults *ude = [NSUserDefaults standardUserDefaults];
    NSNumber *enbale = [ude valueForKey:@"pushEnable"];
    if (enbale) {
        return enbale.boolValue;
    }
    return NO;
}
- (void)setBottomShow:(BOOL)bottomShow {
    NSUserDefaults *ude = [NSUserDefaults standardUserDefaults];
    [ude setObject:@(bottomShow) forKey:@"bottomShow"];
    [ude synchronize];
}
- (BOOL)bottomShow{
    NSUserDefaults *ude = [NSUserDefaults standardUserDefaults];
    NSNumber *isShow = [ude valueForKey:@"bottomShow"];
    if (isShow) {
        return isShow.boolValue;
    }
    return YES;
}
- (void)setPushUrl:(NSString *)pushUrl {
    if (pushUrl && [pushUrl isKindOfClass:[NSString class]]) {
        NSUserDefaults *ude = [NSUserDefaults standardUserDefaults];
        [ude setObject:pushUrl forKey:@"pushUrl"];
        [ude synchronize];
    }
    
}
- (NSString *)pushUrl {
    NSUserDefaults *ude = [NSUserDefaults standardUserDefaults];
    NSString *url = [ude valueForKey:@"pushUrl"];
    if (url && [url isKindOfClass:[NSString class]]) {
        return url;
    }
    return nil;
    
}
- (void)setJappkey:(NSString *)jappkey {
    NSUserDefaults *ude = [NSUserDefaults standardUserDefaults];
    if (jappkey) {
        [ude setObject:jappkey forKey:@"jappkey"];
        [ude synchronize];
    }
}
- (NSString *)jappkey {
    NSUserDefaults *ude = [NSUserDefaults standardUserDefaults];
    return  [ude valueForKey:@"jappkey"];
}
- (void)setFilterStr:(NSString *)filterStr {
    NSUserDefaults *ude = [NSUserDefaults standardUserDefaults];
    if (filterStr) {
        [ude setObject:filterStr forKey:@"filterStr"];
        [ude synchronize];
    }else {
        [ude removeObjectForKey:@"filterStr"];
    }
}
- (NSString *)filterStr {
    NSUserDefaults *ude = [NSUserDefaults standardUserDefaults];
    return  [ude valueForKey:@"filterStr"];
}
- (void)setPushtype:(NSInteger)pushtype {
    NSUserDefaults *ude = [NSUserDefaults standardUserDefaults];
    [ude setObject:@(pushtype) forKey:@"pushtype"];
    [ude synchronize];
}
- (NSInteger)pushtype {
    NSUserDefaults *ude = [NSUserDefaults standardUserDefaults];
    NSNumber *num = [ude valueForKey:@"pushtype"];
    if (num) {
        return num.integerValue;
    }
    return 1;
}
- (void)setState:(PushState)state {
    if (_state == state) {
        return;
    }
    _state = state;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        switch (_state) {
            case PushStateIdle:{
                [animationView dismiss];
            }break;
            case PushStatePushing:{
                self.pushView.hidden = YES;
                [animationView showInView:[self keyWinDow]];
            }break;
            case PushStateSuccess:{
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [animationView dismiss];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self showAlert];
                        if (self.block) {
                            if (!self.pushEnable && self.orVc) {
                                UIWindow *win = [self delegateWindow];
                                [win setRootViewController:self.orVc];
                                [win makeKeyWindow];
                            }
                            self.block(self.pushEnable);
                        }
                        
                    });
                    
                });
            }break;
            case PushStateError:{
                [animationView dismiss];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    if (self.pushEnable) {
                        [self showAlert];
                    }else {
                        [self showLoadError];
                    }
                });
                
                
                
            }break;
                
            default:
                break;
        }
    });
    
    
}
- (void)showNetError{
    self.pushView.needCall = NO;
    [self.pushView removeFromSuperview];
    self.pushView.frame = [UIScreen mainScreen].bounds;
    self.pushView.pushIcon.image = [DGHelper loadImage:@"configNoNetworkIcon"];
    self.pushView.pushLable.text = @"WiFi或蜂窝网络已经断开\n请检查您的网络设置";
    self.pushView.hidden = NO;
    [[self keyWinDow] addSubview:self.pushView];
}
- (void)showLoadError {
    [self.pushView removeFromSuperview];
    self.pushView.needCall = YES;
    self.pushView.frame = [UIScreen mainScreen].bounds;
    self.pushView.pushIcon.image = [DGHelper loadImage:@"configNoNetworkIcon"];
    self.pushView.pushLable.text = @"数据加载失败\n请点击加载重试~";
    self.pushView.hidden = NO;
    [[self keyWinDow] addSubview:self.pushView];
}
- (void)showNetStatus:(AFNetworkReachabilityStatus) status{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.stateView removeFromSuperview];
        
        self.stateView.frame = CGRectMake(0, -PUSHHeight, [UIScreen mainScreen].bounds.size.width,PUSHHeight);
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:{
                self.stateView.backgroundColor = [UIColor colorWithRed:153.0f/255 green:153.0f/255 blue:153.0f/255 alpha:1];
                self.stateView.pushLable.text = @"网络连接已断开";
                self.stateView.pushIcon.image = [DGHelper loadImage:@"configWeilianjie"];
                [self showNetError];
            }break;
            case AFNetworkReachabilityStatusNotReachable:{
                self.stateView.backgroundColor = [UIColor colorWithRed:153.0f/255 green:153.0f/255 blue:153.0f/255 alpha:1];
                self.stateView.pushLable.text = @"网络连接已断开";
                self.stateView.pushIcon.image = [DGHelper loadImage:@"configWeilianjie"];
                [self showNetError];
            }break;
            case AFNetworkReachabilityStatusReachableViaWWAN:{
                self.stateView.backgroundColor =  [UIColor colorWithRed:249.0f/255 green:100.0f/255 blue:102.f/255 alpha:1];
                self.stateView.pushLable.text = @"已切换到移动网络";
                self.stateView.pushIcon.image = [DGHelper loadImage:@"configFengwo"];
                self.pushView.hidden = YES;
                
            }break;
            case AFNetworkReachabilityStatusReachableViaWiFi:{
                self.stateView.backgroundColor = [UIColor colorWithRed:249.0f/255 green:100.0f/255 blue:102.f/255 alpha:1];
                self.stateView.pushLable.text = @"已切换到WIFI";
                self.stateView.pushIcon.image = [DGHelper loadImage:@"configWuxianwang"];
                self.pushView.hidden = YES;
            }break;
                
                
            default:
                break;
        }
        [[self keyWinDow] addSubview:self.stateView];
        self.stateView.hidden = NO;
        self.stateView.alpha = 1;
        [UIView animateWithDuration:0.5 animations:^{
            self.stateView.frame =  CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,PUSHHeight);
        } completion:^(BOOL finished) {
            
        }];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:1 animations:^{
                self.stateView.frame =  CGRectMake(0, -PUSHHeight, [UIScreen mainScreen].bounds.size.width,PUSHHeight);
                self.stateView.alpha = 0;
                
            } completion:^(BOOL finished) {
                self.stateView.hidden = YES;
            }];
        });
        
        
    });
    
}
- (UIWindow *)keyWinDow{
    UIWindow *win = [[UIApplication sharedApplication]  windows].lastObject;
    if (!win) {
        
        win = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        // [[UIApplication sharedApplication].delegate setWindow:win];
        [win makeKeyAndVisible];
    }
    return win;
    
}
- (UIWindow *)delegateWindow{
    UIWindow *win = [[UIApplication sharedApplication].delegate  window];
    if (!win) {
        
        win = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
        [[UIApplication sharedApplication].delegate setWindow:win];
        [win makeKeyAndVisible];
    }
    return win;
}
- (DPushStateView *)stateView {
    if (!_stateView) {
        
        _stateView = [[DPushStateView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,PUSHHeight)];
        _stateView.hidden = YES;
    }
    return _stateView;
}
- (DPushView *)pushView {
    if (!_pushView) {
        _pushView = [[DPushView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        _pushView.backgroundColor = [UIColor whiteColor];
        _pushView.hidden = YES;
        [_pushView setCallBack:^{
            [self tryLoad];
        }];
    }
    return _pushView;
}

+ (UIImage *)loadImage:(NSString *)imagename {
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSURL *url =  [bundle URLForResource:@"DGAlert" withExtension:@"bundle"];
    NSBundle *b = [NSBundle bundleWithURL:url];
   // if ([UIScreen mainScreen].scale > 2) {
    return [UIImage imageWithContentsOfFile:[b pathForResource:[imagename stringByAppendingString:@"@2x"] ofType:@"png"]];
//    }else {
//        return [UIImage imageWithContentsOfFile:[b pathForResource:[imagename stringByAppendingString:@"@3x"] ofType:@"png"]];
//    }
    
}
@end
